package com.example.meituan.activity.man;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.meituan.R;
import com.example.meituan.activity.man.adapter.ImageAdapter;
import com.example.meituan.activity.bean.AdminBean;
import com.example.meituan.activity.bean.ImgBean;
import com.example.meituan.activity.bean.ShopBean;
import com.example.meituan.activity.bean.TypeBean;
import com.example.meituan.dao.AdminDao;
import com.example.meituan.dao.ImgDao;
import com.example.meituan.dao.ShopDao;
import com.example.meituan.dao.TypeDao;
import com.example.meituan.until.FileImgUntil;

import java.util.ArrayList;
import java.util.UUID;

/*
* 添加商品界面
* */
public class addShopActivity extends AppCompatActivity {

    AdminDao adminDao;
    AdminBean currentUser;
    ArrayList<String> imagePaths;
    private ImageAdapter imageAdapter;
    private int shopBean(String businessId,String name,String des,String price,String type,String typeDes){
        String id= UUID.randomUUID().toString().replace("-","");
        saveAllImagesToDatabase(id);
        ShopBean shopBean=new ShopBean();
        shopBean.setDes(des);
        shopBean.setName(name);
        shopBean.setPrice(price);
        shopBean.setId(id);
        shopBean.setType(type);
        shopBean.setBusinessId(businessId);
        shopBean.setTime(System.currentTimeMillis());
        if(!typeDes.isEmpty()){
            String[] lines = typeDes.split("\n");
            for (String line : lines) {
                TypeBean typeBean=new TypeBean();
                String typeId= UUID.randomUUID().toString().replace("-","");
                typeBean.setId(typeId);
                typeBean.setShopId(id);
                typeBean.setTypeDescription(line.trim());
                int b=TypeDao.addType(typeBean);
                if (b == 1) {
                    Toast.makeText(addShopActivity.this, "添加类型成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(addShopActivity.this, "添加类型失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
        int a= ShopDao.addShop(shopBean);
        return a;
    }
    private void saveAllImagesToDatabase(String shopId) {
        for (String path : imagePaths) {
            String id= UUID.randomUUID().toString().replace("-","");
            ImgBean imageBean = new ImgBean();
            imageBean.setImg(path);
            imageBean.setId(id);
            imageBean.setShopId(shopId);
            int a=ImgDao.addImage(imageBean);
            if(a==1){
                Toast.makeText(addShopActivity.this, "保存图片成功", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(addShopActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
            }
        }
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_shop);

        Context context = this;

        SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();


        editor.apply();
        //实现一个返回的功能
        Toolbar toolbar=findViewById(R.id.add_shop_list_toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                                                 @Override
                                                 public void onClick(View v) {
                                                     onBackPressed();//返回功能
                                                     //finish();
                                                 }
                                             }
        );




        androidx.recyclerview.widget.RecyclerView recyclerViewImages = findViewById(R.id.addrecyclerViewImages);
        recyclerViewImages.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        imagePaths = new ArrayList<>();
        imageAdapter = new ImageAdapter(this, imagePaths, (position) -> {
            imagePaths.remove(position);
            imageAdapter.removeImage(position);
        });
        recyclerViewImages.setAdapter(imageAdapter);


        // 添加按钮点击事件
        TextView addButton = findViewById(R.id.add_photo_addshop);
        addButton.setOnClickListener(v -> openMultipleGallery());



        if(adminDao==null){
            adminDao=new AdminDao();
        }



        Spinner spinner = findViewById(R.id.add_shop_list_type);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.shop_type_array));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        EditText nameText=findViewById(R.id.add_shop_list_name);
        EditText desText=findViewById(R.id.add_shop_list_des);
        EditText priceText=findViewById(R.id.add_shop_list_price);
        TextView add=findViewById(R.id.add_shop_list);
        EditText typeDesText=findViewById(R.id.add_shop_list_type_des);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=nameText.getText().toString();
                String des=desText.getText().toString();
                String price=priceText.getText().toString();
                String typeDes=typeDesText.getText().toString();
                boolean isValid=true;

                if(name.isEmpty())
                {
                    Toast.makeText(addShopActivity.this, "商品名称不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                if(price.isEmpty())
                {
                    Toast.makeText(addShopActivity.this, "商品价格不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                if(des.isEmpty())
                {
                    Toast.makeText(addShopActivity.this, "商品描述不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                Object selectedItem = spinner.getSelectedItem();
                String selectedType = selectedItem.toString();
                if (selectedType.isEmpty()) {
                    Toast.makeText(addShopActivity.this, "商品类型不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                if(isValid){
                    currentUser = adminDao.getUserInfo(context);
                    String businessId=currentUser.getUserId();
                    int a = shopBean(businessId,name,des,price,selectedType,typeDes);
                    if (a == 1) {
                        Toast.makeText(addShopActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(addShopActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }
    final ActivityResultLauncher<String[]> multipleContentLauncher = registerForActivityResult(
            new ActivityResultContracts.OpenMultipleDocuments(),
            uris -> {
                if (uris != null && !uris.isEmpty()) {
                    for (Uri uri : uris) {
                        String path = FileImgUntil.getImgPath();
                        FileImgUntil.saveImageBitmapToFile(uri, addShopActivity.this, path);

                        if (path != null) {
                            runOnUiThread(() -> {
                                imagePaths.add(path);
                                imageAdapter.addImage(path);
                            });
                        }
                    }
                }
            });
    private void openMultipleGallery() {
        multipleContentLauncher.launch(new String[]{"image/*"});
    }
}